<template>
  <div>
    <el-upload
      v-model:file-list="values"
      ref="uploadImg"
      list-type="picture-card"
      action="action"
      accept="image/jpg,image/jpeg,image/png"
      multiple
      :auto-upload="false"
      :limit="6"
      :http-request="httpRequest"
      :on-change="handleChange"
      :on-preview="handlePictureCardPreview"
    >
      <el-icon><Plus /></el-icon>
    </el-upload>

    <el-dialog v-model="dialogVisible">
      <img :src="dialogImageUrl" style="max-width: 100%" />
    </el-dialog>
    <!-- {{ value }}{{ values }} -->
  </div>
</template>

<script>
import { uploadFile, filePreview } from "@/api/file";
export default {
  props: {
    value: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      timer: null,
      dialogImageUrl: "",
      dialogVisible: false,
      values: this.value,
    };
  },

  methods: {
    /* 上传之前钩子 */
    handleChange(file) {
      console.log(file);
      console.log(this.values);
      if (file.status === "ready") {
        this.debounce(() => {
          this.httpRequest();
        }, 2000);
      }
    },
    /* 自定义上传 */
    async httpRequest() {
      const fileList = this.values;

      let index = fileList.findIndex(
        (t) => t.status === "ready" && !t.isUpload
      ); //拿到当前上传文件的索引
      try {
        if (index !== -1) {
          const res = await uploadFile(fileList[index].raw);
          if (res.code === 0) {
            const res1 = await filePreview(res.data.minFileName);
            const fileObj = {
              url: res1.data,
              fileUrl: res.data.minFileName,
              name: fileList[index].raw.name,
            };
            fileList[index] = fileObj;
          }
        }
      } catch (error) {
        fileList[index].isUpload = true; //标记已经上传过
        console.log(error, "error");
      } finally {
        this.$emit("update:value", fileList);

        this.httpRequest();
      }
    },
    debounce(func, delay) {
      return (() => {
        if (this.timer) {
          clearTimeout(this.timer);
        }
        this.timer = setTimeout(func, delay);
      })();
    },
    handlePictureCardPreview(uploadFile) {
      this.dialogImageUrl = uploadFile.url;
      this.dialogVisible = true;
    },
  },
};
</script>
<style lang="scss" scoped>
/* el-upload附件列表框去除'按 delete 键可删除'提示 */

::v-deep .el-upload {
  .el-upload-list__item .el-icon-close-tip {
    display: none !important;
  }
}
</style>
